<template>
  <div class="dept-manage-container">
    <div class="page-title">
      <span class="blue-bar"></span>
      <span>部门管理</span>
    </div>
    <el-button type="primary" class="add-btn" @click="openAddDialog">
      <span class="plus">＋</span> 新增部门
    </el-button>
    <el-table :data="deptList" style="width: 100%; margin-top: 16px;" border>
      <el-table-column label="序号" width="80" align="center">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" min-width="120" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" min-width="180" align="center">
        <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <span class="action-btn edit" @click="openEditDialog(scope.row.id)">编辑</span>
          <span class="action-btn delete" @click="handleDelete(scope.row.id)">删除</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="400px" :close-on-click-modal="false">
      <div class="dialog-title">
        <span class="blue-bar"></span>
        <span>{{ dialogTitle }}</span>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" style="margin-top: 16px;">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" maxlength="10" show-word-limit placeholder="请输入部门名称，长度为2-10位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog v-model="deleteDialogVisible" width="350px" :show-close="false">
      <div class="dialog-title">
        <span class="blue-bar"></span>
        <span>提示</span>
      </div>
      <div style="margin: 24px 0 12px 0;">您确定要删除该部门吗？</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
const deptList = ref([])
const loading = ref(false)

function formatDate(val) {
  if (!val) return ''
  return val.replace('T', ' ')
}

// 查询部门列表
async function fetchDepts() {
  loading.value = true
  try {
    const res = await request.get('/depts')
    deptList.value = res.data || []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
onMounted(fetchDepts)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = reactive({ id: null, name: '' })
const formRef = ref()
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度为2-10位', trigger: 'blur' }
  ]
}
let isEdit = false

function openAddDialog() {
  dialogTitle.value = '新增部门'
  form.id = null
  form.name = ''
  isEdit = false
  dialogVisible.value = true
}

async function openEditDialog(id) {
  dialogTitle.value = '编辑部门'
  isEdit = true
  try {
    const res = await request.get(`/depts/${id}`)
    form.id = res.data.id
    form.name = res.data.name
    dialogVisible.value = true
  } catch (e) {
    console.error(e)
  }
}

// 新增/编辑提交
async function handleSubmit() {
  await formRef.value.validate()
  if (isEdit) {
    try {
      // 编辑时需要带上所有字段
      await request.put('/depts', {
        id: form.id,
        name: form.name
      })
      ElMessage.success('修改成功')
      dialogVisible.value = false
      fetchDepts()
    } catch (e) {
      console.error(e)
    }
  } else {
    try {
      await request.post('/depts', { name: form.name })
      ElMessage.success('新增成功')
      dialogVisible.value = false
      fetchDepts()
    } catch (e) {
      console.error(e)
    }
  }
}

// 删除
const deleteDialogVisible = ref(false)
let deleteId = null
function handleDelete(id) {
  deleteId = id
  deleteDialogVisible.value = true
}
async function confirmDelete() {
  try {
    await request.delete(`/depts/${deleteId}`)
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    fetchDepts()
  } catch (e) {
    console.error(e)
  }
}
</script>

<style scoped>
.dept-manage-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}
.page-title {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}
.blue-bar {
  display: inline-block;
  width: 4px;
  height: 22px;
  background: #1890ff;
  margin-right: 8px;
  border-radius: 2px;
}
.add-btn {
  margin-bottom: 16px;
  margin-left: 0;
}
.plus {
  font-size: 18px;
  margin-right: 2px;
}
.action-btn {
  margin: 0 8px;
  cursor: pointer;
}
.action-btn:hover {
  text-decoration: underline;
}
.action-btn.edit {
  color: #4b6ac9; /* 蓝色 */
}
.action-btn.delete {
  color: #d73030; /* 红色 */
}
.dialog-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
</style>